package com.sofwin.configer;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.support.JdbcTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @packageName: com.sofwin.configer
 * @user: andyliu
 * @date: 2022/12/16 10:02
 * @email 115176513@qq.com
 * @description: TODO
 */
@Configuration
@PropertySource("classpath:jdbc.properties")
@MapperScan(basePackages = "com.sofwin.mapper")
@EnableTransactionManagement
public class DaoConfiger {
    private String driveClassName="com.mysql.cj.jdbc.Driver";
    private String url="jdbc:mysql:///rbac2207q";
    private String userName="root";
    private String password="123456";

    // 在applicationContext.xml中有一个bean class=DataSource的实现类
    @Bean
    @Scope("singleton") // bean标签中的scope属性吧
    @Lazy // bean标签中的init-lazy
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driveClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        return dataSource;
    }
    @Bean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(){
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(getDataSource());
        bean.setTypeAliasesPackage("com.sofwin.pojo");
        Resource resource = new ClassPathResource("configer.xml");
        bean.setConfigLocation(resource);
        bean.setPlugins(getInterceptor());
        return bean;
    }
    @Bean
    public PageInterceptor getInterceptor(){
        PageInterceptor interceptor = new PageInterceptor();
        Properties props = new Properties();
        props.setProperty("helperDialect","mysql");
        interceptor.setProperties(props);
        return interceptor;
    }
    @Bean
    public JdbcTransactionManager jdbcTransactionManager(){
        JdbcTransactionManager manager = new JdbcTransactionManager();
        manager.setDataSource(getDataSource());
        return manager;
    }

}
